<?php
/**
 * Created by PhpStorm.
 * User: Jessewang
 * Date: 2017/3/26
 * Time: 下午9:48
 */

namespace App\Service;
use Swoole;
use Swoole\RandomKey;
use App\Libs\TimApi;
use Swoole\Tool;
use App\Service\LikeService;
class MatchService extends BaseService
{

    const  CACHE_KEY_WOMAN =  "online#0";
    const  CACHE_KEY_MAN= "online#1";
    const  CACHE_KEY_CALLLIST= "online#list#";
    const CACHE_KEY_HOT_WOMAN = "online#hot#0";
    const CACHE_KEY_HOT_MAN = "online#hot#1";
    const CACHE_KEY_MATCH = "match#";
    public $timapi;


    function __construct()
    {
        $this->timapi = new TimApi();
    }

    function sendMsg($userid,$destid,$type)
    {

    	if($type == 'like')
    	{
    		$msgcontent = 'I Like U';
    	}
    	else 
    	{
    		$msgcontent = 'I Want U';
    	}
    
    	//创建array 所需元素
    	$msgbody = array(
    			'MsgType' => 'TIMCustomElem',       //自定义
    			'MsgContent' => array(
    					'Data' => $type,
    					"Desc"=>$msgcontent,
    					"Ext"=>"",
    					"Sound"=> ""
    			)
    	);

       // $ret =  $this->timapi->sendMsg($userid,$destid,$msgbody);
        $data['userid'] = $userid;
        $data['destid'] = $destid;
        $data['msgbody'] = $msgbody;
        Swoole::getInstance()->event->trigger('msg',$data);
       // Swoole::getInstance()->event->runWorker(1);
       // var_dump($ret);

    }
    function  addFriend($userid,$destid)
    {
        $ret =  $this->timapi->addFriend($userid,$destid);
        if($ret['ActionStatus']== 'ok')
        {
            return true;
        }
        else
        {
            return false;
        }

    }
    function like($callid,$userid)
    {
        $callinfo =  \Swoole::getInstance()->redis->hGetAll(self::CACHE_KEY_CALLLIST.$callid);
        if($callinfo)
        {
            if($userid == $callinfo['userid'] )
            {

                \Swoole::getInstance()->redis->hSet(self::CACHE_KEY_CALLLIST.$callid,'userlike',1);
                $retinfo['userid'] = $callinfo['userid'];
                $retinfo['peerid'] = $callinfo['peerid'];
            }
            else
            {
                if($userid == $callinfo['peerid'] )
                {

                    \Swoole::getInstance()->redis->hSet(self::CACHE_KEY_CALLLIST.$callid,'peerlike',1);
                    $retinfo['userid'] = $callinfo['peerid'];
                    $retinfo['peerid'] = $callinfo['userid'];
                }
            }
        }

        $ret = $this->sendMsg($callinfo['userid'],$callinfo['peerid'],'like');
         return $retinfo;

    }

    /**
     * @param $callid
     * @param $status  0:开始 1:`通话成功 2：通话失败 3：通话结束
     *
     */
    function updatecallinfo($userid,$callid, $status)
    {
        $callinfo = \Swoole::getInstance()->redis->hGetAll(self::CACHE_KEY_CALLLIST.$callid);

        if($callinfo && $callinfo['status'] !=$status && $status ==3)
        {
            \Swoole::getInstance()->redis->hSet(self::CACHE_KEY_CALLLIST.$callid,'status',$status);

                $usermatchcount = \Swoole::getInstance()->redis->hIncrBy(self::CACHE_KEY_MATCH . $callinfo['userid'], 'matchcount', 1);
                $peermatchcount = \Swoole::getInstance()->redis->hIncrBy(self::CACHE_KEY_MATCH . $callinfo['peerid'], 'matchcount', 1);
                if($callinfo['userlike'] ==1  )
                    $peerscore = 1;
                if($callinfo['usertime'] >1)
                    $peerscore += 0.2;
                if($callinfo['peerlike'] ==1  )
                    $userscore = 1;
                if($callinfo['peertime'] >1)
                    $userscore += 0.2;
                $usermatchcount = \Swoole::getInstance()->redis->hIncrByFloat(self::CACHE_KEY_MATCH . $callinfo['userid'], 'matchscore', $userscore);
                $peermatchcount = \Swoole::getInstance()->redis->hIncrBy(self::CACHE_KEY_MATCH . $callinfo['peerid'], 'matchscore',$peerscore );
        }
    }

    /**
     * @param $callid
     *
     * @return array
     */
    function getcallinfo($callid)
    {
        $callinfo = \Swoole::getInstance()->redis->hGetAll(self::CACHE_KEY_CALLLIST . $callid);
        if ($callinfo) {
            $retinfo['callid'] = $callinfo['callid'];
            $retinfo['userid'] = $callinfo['userid'];
            $retinfo['peerid'] = $callinfo['peerid'];
            $retinfo['alltime'] = $callinfo['alltime'];
        }
        return $callinfo;
    }

    /**
     * @param $callid
     * @param $userid
     * @param $addtimes
     *
     * @return array
     */
    function addtime($callid, $userid, $addtimes)
    {
        $callinfo =  \Swoole::getInstance()->redis->hGetAll(self::CACHE_KEY_CALLLIST.$callid);
        if($callinfo)
        {
            if($userid == $callinfo['userid'] )
            {

               \Swoole::getInstance()->redis->hSet(self::CACHE_KEY_CALLLIST.$callid,'usertime',$callinfo['usertime']+$addtimes);
                $userttime = $callinfo['usertime']+$addtimes;
                $peertime = $callinfo['peertime'];
            }
            else
            {
                if($userid == $callinfo['peerid'] )
                {
                    $userttime =  $callinfo['usertime'];
                    \Swoole::getInstance()->redis->hSet(self::CACHE_KEY_CALLLIST.$callid,'peertime',$callinfo['peertime']+$addtimes);
                    $peertime = $callinfo['peertime']+$addtimes;
                }
            }
        }

        if($userttime !=0 && $peertime !=0)
        {
            $alltime = $this->min($userttime,$peertime);
        }
        else
        {
            $alltime = 0;
        }
       // var_dump($alltime);
        \Swoole::getInstance()->redis->hSet(self::CACHE_KEY_CALLLIST.$callid,'alltime',$alltime);

        $ret = $this->sendMsg($callinfo['userid'],$callinfo['peerid'],'addtime');
        //var_dump($ret);
        return    $this->getcallinfo($callid);
    }


    /**
     * @param $userinfo
     *
     * @return array
     */
    function match($userinfo,$userselect)
    {

        $userid = $userinfo['user_id'];
        $user_sex = $userinfo['user_sex'];
        $user_age = isset($userinfo['user_age'])?$userinfo['user_age']:20;

        if($userselect == 1)
        $peerlist =  \Swoole::getInstance()->redis->zRangeByScore(self::CACHE_KEY_MAN,$user_age-5,$user_age+5);
        else
            $peerlist =  \Swoole::getInstance()->redis->zRangeByScore(self::CACHE_KEY_WOMAN,$user_age-5,$user_age+5);
        foreach( $peerlist as $k=>$v) {
            if($userid == $v) unset($peerlist[$k]);
        }
        //var_dump($peerlist);
        if($peerlist) {
            $index = rand(0, count($peerlist)-1);
           // var_dump($index);
            $peerid = $peerlist[$index];
            $callid = $this->genCallId();


            $tool = new Tool();
            $callinfo['callid'] = $callid;
            $callinfo['userid'] = $userid;
            $callinfo['usertime'] = 0;
            $callinfo['peerid'] = $peerid;
            $callinfo['peertime'] = 0;
            $callinfo['alltime'] = 0;
            $callinfo['status'] = 0;
            $callinfo['calltime'] =  $tool->now();

            \Swoole::getInstance()->redis->hMset(self::CACHE_KEY_CALLLIST . $callid, $callinfo);
            $retinfo['callid'] = $callid;
            $retinfo['userid'] = $userid;
            $retinfo['peerid'] = $peerid;
            $retinfo['alltime'] = $callinfo['alltime'];
            $ret = array(
                "errorcode" =>'0',
                'errmsg'=>"匹配成功",
                'callinfo'=>$retinfo
            );
        }
        else
        {
            $ret = array(
                "errorcode" =>'1',
                'errmsg'=>"匹配失败",
                'callinfo'=>""
            );
        }
        return $ret;
    }

    /**
     * @param $userinfo
     */
    function online($userinfo)
    {
        $userinfoext = \Swoole::getInstance()->redis->hGetAll(self::CACHE_KEY_MATCH.$userinfo['user_id']);
        if(empty($userinfo['user_age']))
        {
            $userinfo['user_age'] = 20;
        }
        if($userinfo['user_sex'] == 0)
        {
            \Swoole::getInstance()->redis->zAdd(self::CACHE_KEY_WOMAN,$userinfo['user_age'],$userinfo['user_id']);
        }
        else
        {
            \Swoole::getInstance()->redis->zAdd(self::CACHE_KEY_MAN,$userinfo['user_age'],$userinfo['user_id']);
        }
        return true;
    }

    /**
     * @param $userinfo
     *
     * @return bool
     */
    function offline($userinfo)
    {
        if($userinfo['user_sex'] == 0)
        {
            \Swoole::getInstance()->redis->zDelete(self::CACHE_KEY_WOMAN,$userinfo['user_id']);
        }
        else
        {
            \Swoole::getInstance()->redis->zDelete(self::CACHE_KEY_MAN,$userinfo['user_id']);
        }
        return true;
    }


    /**
     * @return string
     */
    function genCallId()
    {
        $callid =  RandomKey::randtime(6);
        return $callid;
    }

    /**
     * @param $int1
     * @param $int2
     *
     * @return mixed
     */
    function min($int1, $int2){
        return $int1<$int2?$int1:$int2;
    }

}